/* Includes--------------------------------------------- */
#include "drv_i2c.h"
#include "gd32e23x.h"

/* Define----------------------------------------------- */
#define I2C_OWN_ADDRESS     0x10
#define I2C_PERIPH          I2C1
#define I2C_CLOCK       RCU_I2C1
#define I2C_SPEED         250000//250k
#define I2C_TIMEOUT         1000

/* Private funtion delaration--------------------------- */
/* Private variables------------------------------------ */
/* External variables----------------------------------- */
/* External functions----------------------------------- */
void DrvI2CInit(void) {
    rcu_periph_clock_enable(RCU_GPIOB);
    gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_10 | GPIO_PIN_11);
    gpio_output_options_set(GPIOB,GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_10 | GPIO_PIN_11);
    gpio_af_set(GPIOB, GPIO_AF_1, GPIO_PIN_10 | GPIO_PIN_11);

    rcu_periph_clock_enable(I2C_CLOCK);
    i2c_clock_config(I2C_PERIPH, I2C_SPEED, I2C_DTCY_2);
    i2c_mode_addr_config(I2C_PERIPH, I2C_I2CMODE_ENABLE, I2C_ADDFORMAT_7BITS, I2C_OWN_ADDRESS);
    i2c_ack_config(I2C_PERIPH, I2C_ACK_ENABLE);
//    i2c_ackpos_config(I2C_PERIPH, I2C_ACKPOS_CURRENT);
    i2c_enable(I2C_PERIPH);
}

void DrvI2CWriteByte(uint8_t addr, uint8_t reg, uint8_t data) {
    uint32_t timeout;

    i2c_start_on_bus(I2C_PERIPH);
    timeout = I2C_TIMEOUT;
    while(!i2c_flag_get(I2C_PERIPH, I2C_FLAG_I2CBSY) && timeout--);

    timeout = I2C_TIMEOUT;
    while(!i2c_flag_get(I2C_PERIPH, I2C_FLAG_SBSEND) && timeout--);

    i2c_master_addressing(I2C_PERIPH, addr, I2C_TRANSMITTER);
    timeout = I2C_TIMEOUT;
    while(!i2c_flag_get(I2C_PERIPH, I2C_FLAG_ADDSEND) && timeout--);
    i2c_flag_clear(I2C_PERIPH, I2C_FLAG_ADDSEND);

    timeout = I2C_TIMEOUT;
    while(!i2c_flag_get(I2C_PERIPH, I2C_FLAG_TBE) && timeout--);
    i2c_data_transmit(I2C_PERIPH, reg);

    timeout = I2C_TIMEOUT;
    while(!i2c_flag_get(I2C_PERIPH, I2C_FLAG_TBE) && timeout--);
    i2c_data_transmit(I2C_PERIPH, data);
    timeout = I2C_TIMEOUT;
    while(!i2c_flag_get(I2C_PERIPH, I2C_FLAG_BTC) && timeout--);

    i2c_stop_on_bus(I2C_PERIPH);
}

/* Private functions------------------------------------ */
/* End of file------------------------------------------ */
